package com.simple.space.util;

import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 数据类型判断和比较
 */
public class DataUtil {
	public static final Pattern NUMBER_PATTERN = Pattern
			.compile("^(-?\\d+)(\\.\\d+)?$");
	public static final Pattern INTEGER_PATTERN = Pattern.compile("^-?[\\d]+$");
	public static final Pattern DATE_PATTERN = Pattern
			.compile("^(\\d{4})\\-(\\d{2})\\-(\\d{2})$");
	public static final Pattern TIME_PATTERN = Pattern
			.compile("^(\\d{4})\\-(\\d{2})\\-(\\d{2})\\s(\\d{2}):(\\d{2}):(\\d{2})$");

	/**
	 * 判断字符串是否为空
	 * 
	 * @param param
	 * @return
	 */
	public static boolean isEmpty(String param) {
		return param == null || param.trim().length() == 0;
	}

	/**
	 * 判断字符串不为空
	 * 
	 * @param param
	 * @return
	 */
	public static boolean isNotEmpty(String param) {
		return param != null && param.trim().length() != 0;
	}

	/**
	 * 判断是否为数字
	 * 
	 * @param param
	 * @return
	 */
	public static boolean isNumber(String param) {
		if (param == null)
			return false;
		Matcher m = NUMBER_PATTERN.matcher(param);
		return (m.find());
	}

	/**
	 * 判断是否为整型数字
	 * 
	 * @param param
	 * @return
	 */
	public static boolean isInteger(String param) {
		if (param == null)
			return false;
		Matcher m = INTEGER_PATTERN.matcher(param);

		return (m.find());
	}

	/**
	 * 判断是否为日期字符串（格式如：2014-04-01）
	 * 
	 * @param param
	 * @return
	 */
	public static boolean isDate(String param) {
		if (param != null) {
			Matcher m = DATE_PATTERN.matcher(param);
			if (m.find())
				return true;
		}
		return false;
	}

	/**
	 * 判断是否为时间字符串（格式如：2014-04-01 12:00:00）
	 * 
	 * @param param
	 * @return
	 */
	public static boolean isTime(String param) {
		if (param != null) {
			Matcher m = TIME_PATTERN.matcher(param);
			if (m.find())
				return true;
		}
		return false;
	}

	public static String getJSONStringByList(List<?> list) {
		return getJSONStringByList(list, null);
	}

	/**
	 * 指定字段获取List的JSON格式数据
	 * 
	 * @author 程赞达
	 * @param list
	 *            需要被转换的集合
	 * @param fields
	 *            需要获取的字段
	 * @return String
	 */
	public static String getJSONStringByList(List<?> list, List<String> fields) {
		if (list == null) {
			return null;
		}
		if (fields == null) {
			fields = new ArrayList<String>();
			fields.add("id");
			fields.add("name");
		}
		StringBuilder sb = new StringBuilder();
		sb.append("[");
		for (int i = 0; i < list.size(); i++) {
			Object obj = list.get(i);
			Class<?> c = obj.getClass();
			sb.append("{");
			for (int j = 0; j < fields.size(); j++) {
				String field = fields.get(j);
				try {
					Method m = c.getMethod("get"
							+ field.substring(0, 1).toUpperCase()
							+ field.substring(1), null);
					sb.append("\"" + field + "\":\"" + m.invoke(obj, null)
							+ "\"");
				} catch (Exception e) {
				}
				if (j != fields.size() - 1) {
					sb.append(",");
				}
			}
			sb.append("}");
			if (i != list.size() - 1) {
				sb.append(",");
			}
		}
		sb.append("]");
		return sb.toString();
	}

	/**
	 * JSON字符串转换成对象集合(只支持6种基本数据类型)
	 * 
	 * @author 程赞达
	 * @param c
	 *            集合的对象
	 * @param json
	 *            需要被转换的字符串
	 * @return List
	 */
	public static List<?> getObjectByJSONString(Class<?> c, String json)
			throws Exception {
		if (json.length() <= 2 && json.contains("{") == false) {
			return null;
		}
		json = "," + json.substring(1, json.length() - 1);
		String[] ss = json.split("}");
		List<Object> list = new ArrayList<Object>();
		Field[] f = c.getDeclaredFields();
		for (int i = 0; i < ss.length; i++) {
			String[] arr = ss[i].substring(2).replaceAll("\"", "").split(",");
			Map<String, String> map = getMapByArray(arr);
			Object o = c.newInstance();
			for (int j = 0; j < f.length; j++) {
				String name = f[j].getName();
				String value = map.get(name);
				if (value != null) {
					String setName = "set" + name.substring(0, 1).toUpperCase()
							+ name.substring(1);
					Class<?> ctype = f[j].getType();
					Object val = null;
					if (ctype.equals(String.class)) {
						val = value.toString();
					} else if (ctype.equals(Integer.class)) {
						val = Integer.parseInt(value);
					} else if (ctype.equals(Long.class)) {
						val = Long.parseLong(value);
					} else if (ctype.equals(Double.class)) {
						val = Double.parseDouble(value);
					} else if (ctype.equals(Float.class)) {
						val = Float.parseFloat(value);
					} else if (ctype.equals(Boolean.class)) {
						val = Boolean.parseBoolean(value);
					} else if (ctype.equals(Short.class)) {
						val = Short.parseShort(value);
					}
					if (val != null) {
						o.getClass().getMethod(setName, ctype).invoke(o, val);
					}
				}
			}
			list.add(o);
		}
		return list;
	}

	/**
	 * 一个单元的json字符串转换成MAP对象
	 * 
	 * @methodName: getMapByArray
	 * @param:
	 * @author: 程赞达
	 * @date: Jul 16, 2011 8:35:23 PM
	 * @return:
	 * @throws:
	 */
	public static Map<String, String> getMapByArray(String[] arr) {
		Map<String, String> map = new HashMap<String, String>();
		for (int i = 0; i < arr.length; i++) {
			int pos = arr[i].indexOf(":");
			map.put(arr[i].substring(0, pos), arr[i].substring(pos + 1));
		}
		return map;
	}

	/**
	 * 数组转换成集合
	 * 
	 * @param strs String[]
	 * @return
	 */
	public static List<String> arrayToList(String[] strs) {
		List<String> list = new ArrayList<String>();
		if (strs != null && strs.length > 0) {
			for (String str : strs) {
				list.add(str);
			}
		}
		return list;
	}

	/**
	 * List深拷贝
	 * 
	 * @param src
	 * @return
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public static List deepCopy(List src) throws IOException,
			ClassNotFoundException {
		ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
		ObjectOutputStream out = new ObjectOutputStream(byteOut);
		out.writeObject(src);
		ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut
				.toByteArray());
		ObjectInputStream in = new ObjectInputStream(byteIn);
		List dest = (List) in.readObject();
		return dest;
	}

	/**
	 * 字符串转换为short
	 * 
	 * @param val
	 *            原始值
	 * @return 返回值>0，表示成功，失败返回0
	 */
	public static short parseShort(String val) {
		short result = 0;

		try {
			result = Short.parseShort(val);
		} catch (Exception e) {

		}
		return result;
	}

	/**
	 * 字符串转换为short，可以设置默认值
	 * 
	 * @param val
	 *            原始值
	 * @param def
	 *            默认值
	 * @return 返回值>0，表示成功，失败返回默认值
	 */
	public static short parseShortDef(String val, short def) {
		short result = def;

		try {
			result = Short.parseShort(val);
		} catch (Exception e) {

		}
		return result;
	}

	/**
	 * 字符串转换为int
	 * 
	 * @param val
	 *            原始值
	 * @return 返回值>0，表示成功，失败返回0
	 */
	public static int parseInt(String val) {
		int result = 0;

		try {
			result = Integer.parseInt(val);
		} catch (Exception e) {

		}
		return result;
	}

	/**
	 * 字符串转换为int，可以设置默认值
	 * 
	 * @param val
	 *            原始值
	 * @param def
	 *            默认值
	 * @return 返回值>0，表示成功，失败返回默认值
	 */
	public static int parseIntDef(String val, int def) {
		int result = def;

		try {
			result = Integer.parseInt(val);
		} catch (Exception e) {

		}
		return result;
	}

	/**
	 * 字符串转换为long
	 * 
	 * @param val
	 *            原始值
	 * @return 返回值>0，表示成功，失败返回0
	 */
	public static long parseLong(String val) {
		long result = 0;

		try {
			result = Long.parseLong(val);
		} catch (Exception e) {

		}
		return result;
	}

	/**
	 * 字符串转换为long，可以设置默认值
	 * 
	 * @param val
	 *            原始值
	 * @param def
	 *            默认值
	 * @return 返回值>0，表示成功，失败返回默认值
	 */
	public static long parseLongDef(String val, long def) {
		long result = def;

		try {
			result = Long.parseLong(val);
		} catch (Exception e) {

		}
		return result;
	}

	/**
	 * 字符串转换为double
	 * 
	 * @param val
	 *            原始值
	 * @return 返回值>0，表示成功，失败返回0
	 */
	public static double parseDouble(String val) {
		double result = 0;

		try {
			result = Double.parseDouble(val);
		} catch (Exception e) {

		}
		return result;
	}

	/**
	 * 字符串转换为double，可以设置默认值
	 * 
	 * @param val
	 *            原始值
	 * @param def
	 *            默认值
	 * @return 返回值>0，表示成功，失败返回默认值
	 */
	public static double parseDoubleDef(String val, double def) {
		double result = def;

		try {
			result = Double.parseDouble(val);
		} catch (Exception e) {

		}
		return result;
	}

	/**
	 * Integer转换成short
	 * 
	 * @param val
	 * @return
	 */
	public static short toShortValue(Integer val) {
		short result = 0;

		if (val != null) {
			try {
				result = val.shortValue();
			} catch (Exception e) {

			}
		}
		return result;
	}

	/**
	 * Integer转换成byte
	 * 
	 * @param val
	 * @return
	 */
	public static byte toByteValue(Integer val) {
		byte result = 0;

		if (val != null) {
			try {
				result = val.byteValue();
			} catch (Exception e) {

			}
		}
		return result;
	}

	/**
	 * Long转换成int
	 * 
	 * @param val
	 * @return
	 */
	public static int toIntValue(Long val) {
		int result = 0;

		if (val != null) {
			try {
				result = val.intValue();
			} catch (Exception e) {

			}
		}
		return result;
	}

	/**
	 * 保留小数位数到指定位数
	 * 
	 * @param value
	 *            要处理的值
	 * @param digit
	 *            小数位数
	 * @return
	 */
	public static double convertDecimal(double value, int digit) {
		BigDecimal b = new BigDecimal(value);
		double retValue = b.setScale(digit, BigDecimal.ROUND_HALF_UP)
				.doubleValue();
		return retValue;
	}

	public static String convertDecimalToStr(double value, int digit) {
		BigDecimal b = new BigDecimal(value);
		String retValue = b.setScale(digit, BigDecimal.ROUND_HALF_UP)
				.toPlainString();
		return retValue;
	}

	/**
	 * 保留小数位数到指定位数
	 * 
	 * @param value
	 *            要处理的值
	 * @param digit
	 *            小数位数
	 * @return
	 */
	public static String convertDecimalStr(double value, int digit) {
		BigDecimal b = new BigDecimal(value);
		double retValue = b.setScale(digit, BigDecimal.ROUND_HALF_UP)
				.doubleValue();
		return String.valueOf(retValue);
	}

	/**
	 * 判断一个数是否在指定范围内
	 * 
	 * @param value
	 *            要判断的值
	 * @param start
	 *            最小值
	 * @param end
	 *            最大值
	 * @param type
	 *            类型:1:不包含 2:包含
	 * @return
	 */
	public static boolean withinRange(long value, long start, long end, int type) {
		if (type == 2) {
			if (value >= start && value <= end) {
				return true;
			} else {
				return false;
			}
		} else {
			if (value > start && value < end) {
				return true;
			} else {
				return false;
			}
		}
	}

	// public static void main(String[] args) {
	// int num1 = 7;
	//		  
	// int num2 = 9;
	//  
	// // 创建一个数值格式化对象
	//  
	// NumberFormat numberFormat = NumberFormat.getInstance();
	//  
	// // 设置精确到小数点后2位
	//  
	// numberFormat.setMaximumFractionDigits(2);
	//  
	// String result = numberFormat.format((float) num1 / (float) num2 * 100);
	//  
	// System.out.println("num1和num2的百分比为:" + result + "%");
	// }

	/**
	 * 边界值类型
	 */
	public static final int BYTE_BOUNDARY_DWORD = 1;
	public static final int BYTE_BOUNDARY_WORD = 2;
	public static final int BYTE_BOUNDARY_BYTE_FF = 3;
	public static final int BYTE_BOUNDARY_BYTE = 4;
	
	public static final int BYTE_BOUNDARY_QWORD = 5;

	/**
	 * 判断value是否达到边界值
	 * 
	 * @param value
	 * @param type
	 * @return
	 */
	public static boolean byteBoundary(long value, int type) {
		boolean result = false;

		switch (type) {
		case BYTE_BOUNDARY_DWORD:
			result = (value == 0xFFFFFFFFL || value == 0xFFFFFFFF
					|| value == 0xFFFFFFFEL || value == 0xFFFFFFFE);
			break;
		case BYTE_BOUNDARY_WORD:
			result = (value == 0xFFFFL || value == 0xFFFF || value == 0xFFFEL || value == 0xFFFE);
			break;
		case BYTE_BOUNDARY_BYTE_FF:
			result = (value == 0xFFL || value == 0xFF);
			break;
		case BYTE_BOUNDARY_BYTE:
			result = (value == 0xFEL || value == 0xFE || value == 0xFFL || value == 0xFF);
			break;
		case BYTE_BOUNDARY_QWORD:
			result = (value == 0xFFFFFFFFFFFFFFFFL 
					|| value == 0xFFFFFFFFFFFFFFFEL );
			break;
		}

		return result;

	}

	/**
	 * 修正参数乱码
	 * 
	 * @param str
	 * @return
	 */
	public static String encodeStr(String str) {
		try {
			return new String(str.getBytes("ISO-8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 计算进度
	 * 
	 * @param total
	 *            总数
	 * @param count
	 *            当前执行了多少
	 * @param percent
	 *            占比
	 * @return
	 */
	public static String calProgress(int total, int count, double percent) {
		// 创建一个数值格式化对象
		NumberFormat numberFormat = NumberFormat.getInstance();
		// 设置精确到小数点后2位
		numberFormat.setMaximumFractionDigits(0);

		String progress = numberFormat
				.format(((float) count / (float) total * 100) * percent);
		// int progress = (count/total)*100;
		return progress;
	}

	/**
	 * 去重
	 * 
	 * @param data
	 * @return
	 */
	public static List<String> deDuplication(List<String> data) {
		Set<String> set = new HashSet<String>();
		List<String> result = new ArrayList<String>();
		for (int i = 0; i < data.size(); i++) {
			set.add(data.get(i));
		}
		Iterator<String> it = set.iterator();
		while (it.hasNext()) {
			result.add(it.next());
		}
		return result;
	}

	/**
	 * 去重
	 * 
	 * @param data
	 *            Integer类型数组
	 * @return
	 */
	public static List<Integer> deDuplicationInt(List<Integer> data) {
		Set<Integer> set = new HashSet<Integer>();
		List<Integer> result = new ArrayList<Integer>();
		for (int i = 0; i < data.size(); i++) {
			set.add(data.get(i));
		}
		Iterator<Integer> it = set.iterator();
		while (it.hasNext()) {
			result.add(it.next());
		}
		return result;
	}
	
	
	// 提取以分隔符 split 分隔的 index 项字符串, 其中:
	// 参数:
	// str 源字符串
	// split 分隔符
	// index 索引项, 从 0 开始
	// from 字符串 str 的开始索引, 从 0 开始
	// to 字符串 str 的结束索引, 不含此索引, 若 < 0 则到字符串末尾
	public static String splitString(String str, char split, int index,
			int from, int to) {
		// 初始化
		String result = null;
		int intLen = (str != null) ? str.length() : 0;

		// 校正 to
		if ((to < 0) || (to > intLen)) {
			to = intLen;
		}
		// 0123456789
		// 123,34,3423,||,||1||3||4
		// 检查参数
		if ((index >= 0) && (from >= 0)) {
			for (; to - from > index; index--) {
				int intPos = str.indexOf(split, from);// 3
				if ((intPos >= 0) && (intPos < to)) {
					if (index == 0) {
						result = str.substring(from, intPos);
						break;
					}

					// 下一项
					from = intPos + 1;
				} else if (index == 0) {
					result = str.substring(from, to);
					break;
				} else {
					break;
				}
			}
		}
		// 返回结果
		return result;
	}

	public static String splitString(String str, char ch, int index, int from) {
		return splitString(str, ch, index, from, -1);
	}

	public static String splitString(String str, char ch, int index) {
		return splitString(str, ch, index, 0, -1);
	}

	public static String splitString(String str, char ch) {
		return splitString(str, ch, 0, 0, -1);
	}
	
	/**
	 * 按照给定的字符拆分字符串(末尾若是分隔符 则丢弃)
	 * 
	 * @param itemStr
	 *            需要拆分的字符串
	 * @param split
	 *            正则表达式
	 * @return
	 */
	public static String[] splitString(String itemStr, String split) {
		String[] destArr = null;

		List<String> list = new ArrayList<String>(100);
		if (itemStr != null && itemStr.length() > 0 && split != null
				&& split.length() > 0) {
			int itemLen = itemStr.length();
			int splitLen = split.length();
			int splitFrom = 0;
			while (splitFrom < itemLen) {
				int splitTo = itemStr.indexOf(split, splitFrom);
				if (splitTo >= 0) {
					list.add(itemStr.substring(splitFrom, splitTo));
					splitFrom = splitTo + splitLen;// 下一项
				} else {
					list.add(itemStr.substring(splitFrom, itemLen));// 添加末尾
					break;
				}
			}
		}
		if (list != null && list.size() > 0) {
			destArr = new String[list.size()];
			list.toArray(destArr);
		}
		return destArr;
	}
	
	
	/**
	 * 完整字符串
	 * @param source　源字符串
	 * @param pos　位置1-加在前面　2-加在后面
	 * @param destLen　目标字符串长度
	 * @param str　需要补充的字符串
	 * @return
	 */
	public static String completeStr(String source, int pos, int destLen,
			String str) {
		if (source == null || str == null) {
			return null;
		}
		int len = source.length();
		if (len >= destLen) {
			return source;
		}

		StringBuilder sBuilder = new StringBuilder();
		sBuilder.append(source);

		while (sBuilder.length() < destLen) {
			if (pos == 1) {
				sBuilder.insert(0, str);
			} else {
				sBuilder.append(str);
			}
		}
		return sBuilder.toString();
	}
	
	/**
	 * 计算字符串长度，中文算两个字符
	 *
	 * @param value
	 * @return
	 */
	public static int countStrLength(String value) {
		if (StringUtils.isBlank(value)) {
			return 0;
		}

		int valueLength = 0;
		String chinese = "[\u0391-\uFFE5]";
		/* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
		for (int i = 0; i < value.length(); i++) {
			/* 获取一个字符 */
			String temp = value.substring(i, i + 1);
			/* 判断是否为中文字符 */
			if (temp.matches(chinese)) {
				/* 中文字符长度为2 */
				valueLength += 2;
			} else {
				/* 其他字符长度为1 */
				valueLength += 1;
			}
		}
		return valueLength;
	}
	
	/**
	 * 判断字符串是否符合电话格式
	 *
	 * @param number
	 *            字符串
	 * @param type
	 *            0:固话手机号都需要校验 1：固话 2：手机号
	 * @return
	 */
	public static boolean matchPhone(String number, int type) {
		if (StringUtils.isEmpty(number)) {
			return false;
		}

		if (type == 1) {
			Matcher m = null;
			Pattern p = Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$"); // 验证带区号的,中间有"-"
			// p = Pattern.compile("^[1-9]{1}[0-9]{5,8}$"); // 验证没有区号的
			m = p.matcher(number);
			return m.matches();
		} else if (type == 2) {
			// 符合返回true
			if (Pattern
					.matches(
							"^(1[0-9][0-9])\\d{8}$",
							number)) {
				return true;
			}
		} else {
			boolean phone = false;
			Pattern p = Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$"); // 验证带区号的,中间有"-"
			// p = Pattern.compile("^[1-9]{1}[0-9]{5,8}$"); // 验证没有区号的
			phone = p.matcher(number).matches();

			boolean tel = Pattern
					.matches(
							"^(1[0-9][0-9])\\d{8}$",
							number);

			return phone || tel;
		}
		return false;
	}
	
	public static String replaceFirst(String srcStr, String delStr) {
		String newStr = srcStr.replaceFirst("^"+delStr+"*", ""); 
		return newStr;
//		String str = "000000001234034120";
//		String newStr = str.replaceAll("^(0+)", "");
//		System.out.println(newStr);
	}
	
	public static void main(String[] args) {
		System.out.println(replaceFirst("00011001222333400","0"));
	}
}
